package com.windgo.controller.wx;

import com.windgo.bean.MarketStorage;
import com.windgo.bean.common.BaseRespVo;
import com.windgo.bean.common.CommonData;
import com.windgo.service.WxStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("wx/storage")
public class WxStorageController {
    @Autowired
    WxStorageService wxStorageService;

    @RequestMapping("upload")
    public BaseRespVo<CommonData<MarketStorage>> storageUpload(MultipartFile file) throws IOException {
        //获取文件的名称转为hash值作为key
        UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();
        String uuidName = uuidString.replace("-", "");
        String fileName = file.getName();
        //获取到原始文件名称（name）
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.indexOf(".");
        String endStr = originalFilename.substring(index);
        fileName = uuidName  + fileName + endStr;
        //获取文件的类型（type）
        String contentType = file.getContentType();
        //获取文件的大小（size）
        long size = file.getSize();
        int fileSize = Long.valueOf(size).intValue();
        String pathName = "http://localhost:8083/wx/storage/fetch/"+fileName;
        //获取到文件的访问链接（就是保存的地址）
        File file1 = new File("/Users/cc/Desktop/image",fileName);
        file.transferTo(file1);
        MarketStorage marketStorage = new MarketStorage(fileName, originalFilename, contentType, fileSize, pathName, false);
        int number = wxStorageService.uploadStorage(marketStorage);
        Integer id = marketStorage.getId();
        MarketStorage fileMarketStorage = wxStorageService.queryMarketStorage(id);
        return BaseRespVo.ok(fileMarketStorage);
    }
}
